<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <el-button type="primary" size="small" @click="add()">添加</el-button>
      <!-- <el-button type="primary" size="small" @click="save()">保存</el-button> -->
      <el-divider direction="horizontal" content-position="left"></el-divider>
      <el-form
        :model="{ logicList }"
        ref="form"
        label-width="0px"
        :show-message="false"
      >
        <div v-for="(item, index) in logicList" :key="item.id + index">
          <el-row type="flex" align="center">
            <el-form-item
              :prop="'logicList.' + index + '.id'"
              :rules="[{ required: true, message: ' ' }]"
            >
              <el-select
                size="small"
                v-model="item.id"
                @change="questionChange(item.id, index)"
                placeholder="请选择问题"
              >
                <el-option
                  :key="q.id"
                  v-for="q in questionList"
                  :label="q.label"
                  :value="q.value"
                >
                </el-option> </el-select
            ></el-form-item>

            <span style="margin: 0 10px"> 符合以下 </span>
            <el-select size="small" v-model="item.type" placeholder="请选择">
              <el-option label="全部" :value="0"></el-option>
              <el-option label="任意" :value="1"></el-option>
            </el-select>
            <span style="margin: 0 10px"> 条件时显示此问题： </span>
          </el-row>

          <el-row
            v-for="(item1, index1) in item.list"
            :key="index1"
            type="flex"
            align="center"
          >
            <el-select size="small" v-model="item1.type" placeholder="请选择">
              <el-option label="选中" :value="0"></el-option>
              <el-option label="未选中" :value="1"></el-option>
            </el-select>
            <el-divider
              direction="vertical"
              content-position="left"
            ></el-divider>
            <el-form-item
              :prop="'logicList.' + index + '.list.' + index1 + '.choose'"
              :rules="[{ required: true, message: ' ' }]"
            >
              <el-cascader
                size="small"
                v-model="item1.choose"
                placeholder="请选择"
                :options="choiceList"
              >
              </el-cascader>
            </el-form-item>

            <el-button
              @click="addOption(item)"
              type="text"
              size="default"
              style="font-size: 20px"
              icon="el-icon-circle-plus-outline"
            ></el-button>
            <el-button
              @click="delOption(index1, item, index)"
              type="text"
              size="default"
              style="font-size: 20px; color: #f56c6c"
              icon="el-icon-remove-outline"
            ></el-button>
          </el-row>

          <el-divider
            direction="horizontal"
            content-position="left"
          ></el-divider>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getSurveyById } from "@/api/index";
import { save, update, getSurvey } from "@/api/form";
import md5 from "js-md5";

export default {
  data() {
    return {
      id: null,
      logicList: [],
      formList: [],
      questionList: [],
      choiceList: [],
      currentMD5: null,
    };
  },

  created() {
    if (this.$route.query.id) {
      this.id = this.$route.query.id;
      getSurveyById(this.id).then((res) => {
        this.logicList = JSON.parse(res.logic);
        this.currentMD5 = md5(res.logic);
        this.formList = JSON.parse(res.text);
        this.title = res.title;
        this.questionList = this.formList.map((i) => {
          return {
            value: i.id,
            label: i.num + "." + i.title.replace(/<.*?>/g, ""),
          };
        });
        this.questionList.splice(0, 1);
        for (let i = 0; i < this.formList.length; i++) {
          const e = this.formList[i];
          if (e.type == 3)
            this.choiceList.push({
              value: e.id,
              label: e.num + "." + e.title.replace(/<.*?>/g, ""),
              children: e.options,
            });
        }
      });
    }
  },

  beforeRouteLeave(to, from, next) {
    const loading = this.$loading({
      lock: true,
      text: "保存中....",
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.7)",
    });
    this.save().then((res) => {
      if (res) {
        next();
      } else {
        next(false);
      }
      loading.close();
    });
  },

  methods: {
    add() {
      this.logicList.push({
        id: null,
        type: 0,
        list: [{ id: null, answer: null, choose: [], type: 0 }],
      });
    },
    async save() {
      let t = null;
      this.$refs.form.validate((res) => {
        t = res;
      });

      if (!t) {
        this.$notify({
          title: "提示",
          message: "请填写完整",
          type: "error",
          duration: "2000",
          position: "top-right",
          showClose: "true",
        });
        return false;
      }

      let bak = this.logicList;

      for (let i = 0; i < bak.length; i++) {
        for (let j = 0; j < bak[i].list.length; j++) {
          bak[i].list[j].id = bak[i].list[j].choose[0];
          bak[i].list[j].answer = bak[i].list[j].choose[1];
        }
      }

      let m = md5(JSON.stringify(this.logicList));

      if (m == this.currentMD5) return true;

      const [err, res] = await update(this.id, {
        text: JSON.stringify(this.formList),
        logic: JSON.stringify(bak),
        title: this.title,
      })
        .then((res) => [null, res])
        .catch((err) => [err, null]);

      if (err) {
        this.$notify({
          title: "提示",
          message: "保存逻辑失败",
          type: "error",
          duration: "2000",
          position: "top-right",
          showClose: "true",
        });
      }

      this.currentMD5 = m;
      this.$notify({
        title: "提示",
        message: "保存逻辑成功",
        type: "success",
        duration: "4500",
        position: "top-right",
        showClose: "true",
      });

      return true;
    },
    addOption(item) {
      item.list.push({ id: null, answer: null, type: 0 });
    },
    delOption(index, item, index1) {
      item.list.splice(index, 1);
      if (item.list.length == 0) {
        this.del(index1);
      }
    },
    del(index) {
      this.logicList.splice(index, 1);
    },
    questionChange(e, index) {
      this.choiceList.map((i) => {
        i.value == e ? (i.disabled = true) : (i.disabled = false);
      });
      this.logicList[index].list.splice(1, this.logicList[index].list.length);
      this.logicList[index].list[0].choose = [];
    },
  },
};
</script>

<style scoped>
.el-card {
  height: 84vh;
}
.el-row--flex {
  align-items: center;
}
.el-form-item {
  margin: 0;
}
</style>